package cn.fbs.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @program: qbservices
 * @description: 类描述
 * @author: hc
 * @create: 2021-01-28 21:23
 **/
public class DownloadUtil {

  public static void download(File file, HttpServletResponse res) {
    BufferedInputStream br = null;
    OutputStream out = null;
    try {
      if (!file.exists()) {
        res.sendError(522, "File not found!");
        return;
      }
      br = new BufferedInputStream(new FileInputStream(file));
      byte[] buf = new byte[1024];
      int len = 0;

      res.reset();
      //res.setContentType("application/x-msdownload");
      res.setContentType("multipart/form-data");
      String fileName=file.getName();
      String substring = fileName.substring(fileName.lastIndexOf("/") + 1);
      res.setHeader("Content-Disposition",
          "attachment; filename=" + new String(substring.getBytes("UTF-8"),
              "ISO-8859-1"));//转码，否则容易乱码
      res.setCharacterEncoding("UTF-8");
      out = res.getOutputStream();
      while ((len = br.read(buf)) > 0) {
        out.write(buf, 0, len);
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
